package top.yehot.cmmu.spring.interceptor;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import top.yehot.cmmu.spring.anns.ResponseResult;

/**
 *  请求拦截器（标记那些请求返回值需要封装）
 *  
 * @author lquan
 * @date 2022年4月2日 下午3:23:17
 */
public class ResponseResultInterceptor implements HandlerInterceptor {

	// 标记名称
	public static final String RESPONSE_RESULT_ANN = "RESPONSE-RESULT-ANN";
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (handler instanceof HandlerMethod) {
			final HandlerMethod handlerMethod = (HandlerMethod) handler;
			final Class<?> clazz = handlerMethod.getBeanType();
			final Method method = handlerMethod.getMethod();
			// 判断是否在内对象上面加了注解
			if (clazz.isAnnotationPresent(ResponseResult.class)) {
				ResponseResult rrs = clazz.getAnnotation(ResponseResult.class);
				List<String> excludeList = Arrays.asList(rrs.exclude());
				
				if (!excludeList.stream().anyMatch(m -> m.equals(method.getName()))) {
					request.setAttribute(RESPONSE_RESULT_ANN, clazz.getAnnotation(ResponseResult.class));
				}
			} else if (method.isAnnotationPresent(ResponseResult.class)) { // 判断方法体上是否有注解
				request.setAttribute(RESPONSE_RESULT_ANN, method.getAnnotation(ResponseResult.class));
			}
		}
		return true;
	}
	
}
